/**
 * 功能:发票附件 控制器类
 * 开发人员:chengd
 * 创建时间:2012/4/30 22:21:47
 */
package com.towker.frame.controller.sell;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Customs;
import com.towker.frame.model.basicData.Departments;
import com.towker.frame.model.basicData.Invoices;
import com.towker.frame.model.sell.InvoiceAttachment;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.service.basicData.CompaniesService;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.InvoicesService;
import com.towker.frame.service.basicData.PersonService;
import com.towker.frame.service.basicData.SellInvoiceMosService;
import com.towker.frame.service.sell.InvoiceAttachmentService;
import com.towker.frame.service.warehouse.SendBillsService;
import com.towker.frame.share.sys.user.UserShare;
import com.towker.web.MyRequest;

//发票附件
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/sell")
public class InvoiceAttachmentController extends BaseController
{
	private InvoiceAttachmentService service;
	private DepartmentsService departmentsService;
	private DepotsService depotsService;
	private SellInvoiceMosService sellInvoiceMosService;
	private CustomsService customsService;//客户信息
	private SendBillsService sendBillsService;
	private PersonService personService;
	private CompaniesService companiesService;
	private InvoicesService invoicesService;
	
	public void setCompaniesService(CompaniesService companiesService) {
		this.companiesService = companiesService;
	}

	public void setDepartmentsService(DepartmentsService departmentsService) {
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService) {
		this.depotsService = depotsService;
	}

	public void setSellInvoiceMosService(SellInvoiceMosService sellInvoiceMosService) {
		this.sellInvoiceMosService = sellInvoiceMosService;
	}
	
	//业务对象注入
	public void setSendBillsService(SendBillsService sendBillsService)
	{
		this.sendBillsService = sendBillsService;
	}
	
	public void setCustomsService(CustomsService customsService)
	{
		this.customsService = customsService;
	}

	//业务对象注入
	public void setInvoiceAttachmentService(InvoiceAttachmentService service)
	{
		this.service = service;
	}
	
	public void setPersonService(PersonService personService)
	{
		this.personService = personService;
	}

	public void setInvoicesService(InvoicesService invoicesService) {
		this.invoicesService = invoicesService;
	}

	//添加
	@RequestMapping("/addInvoiceAttachment{viewName}")
	public ModelAndView addInvoiceAttachment(HttpServletRequest request, HttpServletResponse response, InvoiceAttachment po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			List<Invoices> invoices = invoicesService.getList(map);
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			List personList = personService.findByCoCode(UserShare.getCurrentUserCoCode(request));  //人员信息
			result.addObject("personList",personList);
			result.addObject("customCodes",customCodes);
			result.addObject("sell_dep_code", UserShare.getCurrentUserDepCode(request));
			result.addObject("mos_codes", sellInvoiceMosService.getList(new HashMap()));
			result.addObject("invoices", invoices);
			
			result.setViewName("/manage/sell/addInvoiceAttachment.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				po.setAttach_code(service.getNewAttachCode());
				po.setInvoice_num(invoicesService.getNextInvoiceNum(po.getInvoice_code()));
				po.setCreate_time(new Date());
				po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
				//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
				service.add(po);
				String goodsInfo = req.getString("goodsInfo");
				processRefGoods(request, RefGoodsType.INVOICE_ATTACHMENT_GOODS, po.getId(), goodsInfo);
				writer.write("添加发票附件成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加发票附件失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delInvoiceAttachment")
	public void delInvoiceAttachment(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		service.delByIds(CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0)));
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updInvoiceAttachment{viewName}")
	public ModelAndView updInvoiceAttachment(HttpServletRequest request, HttpServletResponse response, InvoiceAttachment po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			List<Invoices> invoices = invoicesService.getList(map);
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			List personList = personService.findByCoCode(UserShare.getCurrentUserCoCode(request));  //人员信息
			result.addObject("personList",personList);
			result.addObject("customCodes", customCodes);
			result.addObject("invoices", invoices);
			result.addObject("mos_codes", sellInvoiceMosService.getList(new HashMap()));
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.INVOICE_ATTACHMENT_GOODS.getValue(), new Integer(String.valueOf(id)));
			result.addObject("refGoods", refGoods);
			result.setViewName("/manage/sell/updInvoiceAttachment.jsp");
		}
		else if ("2".equals(viewName))
		{
			String goodsInfo = req.getString("goodsInfo");
			PrintWriter writer = response.getWriter();
			try
			{
				if (req.getInt("old_invoice_code") != po.getInvoice_num()) {
					po.setInvoice_num(invoicesService.getNextInvoiceNum(po.getInvoice_code()));
				}
				
				service.update(po);
				processRefGoods(request, RefGoodsType.INVOICE_ATTACHMENT_GOODS, po.getId(), goodsInfo);
				writer.write("修改发票附件成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改发票附件失败！" + e.getCause());
			}
		}
		return result;
	}

	//获得分页
	@RequestMapping("/getInvoiceAttachment")
	public ModelAndView getInvoiceAttachment(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属公司及部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<InvoiceAttachment> pageModel = service.getPage(page, pageSize, map);
		for(int i=0;i<pageModel.getResult().size();i++){
			String code = pageModel.getResult().get(i).getCustom_code();
			pageModel.getResult().get(i).setCustoms_name(customsService.getCustomName(false, 0, code));
		}
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/sell/getInvoiceAttachment.jsp");
		return result;
	}
	
	
	
	//获得已经审核通过并未复制的发货单分页
	@RequestMapping("/getCopySendBills")
	public ModelAndView getSendBills(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		map.put("audit_status", "1");
		map.put("copy_status", "0");
		//只查询当前用户所属公司及部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<SendBills> pageModel = sendBillsService.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		Map parMap = new HashMap();
		List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
		List companiesList = companiesService.getList(parMap);
		List customsList = customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));// 客户信息
		result.addObject("customsList", customsList);
		result.addObject("personList",personService.findByCoCode(UserShare.getCurrentUserCoCode(request)));//人员信息
		result.addObject("mos_codes", sellInvoiceMosService.getList(new HashMap()));
		result.addObject("departList", departList);
		result.addObject("companiesList",companiesList);
		result.addObject("co_code", UserShare.getCurrentUserCoCode(request)+"["+UserShare.getCurrentUserCoName(request)+"]");
		result.setViewName("/manage/sell/getCopySendBills.jsp");
		return result;
	}
	
	
	//批量复制数据
	@RequestMapping("/copyInvoiceAttach")
	public void copyData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		MyRequest req = new MyRequest(request);
		String payee = req.getString("payee");
		String mos_code = req.getString("mos_code");
		Integer invoice_type = req.getInt("invoice_type");
		String invoice_code = req.getString("invoice_code");
		Integer invoice_num = req.getInt("invoice_num");
		Date create_date = req.getDate("create_date");
		String acc_period = req.getString("acc_period");
		String sell_dep_code = req.getString("sell_dep_code");
		Departments dep = departmentsService.getByCode(sell_dep_code);
		Integer sell_dep_id = 0;
		if (dep != null) {
			sell_dep_id = dep.getId();
		}
		
		Long[] idArry = CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0));
		for (int i = 0; i < idArry.length; i++) {
			Long id = idArry[i];
			SendBills po  = sendBillsService.getById(id);
		//1.复制到发票附件
			po.setCopy_status(1);
			sendBillsService.update(po);
			InvoiceAttachment invoiceAttachment = new InvoiceAttachment();
			invoiceAttachment.setPayee(payee);
			invoiceAttachment.setMos_code(mos_code);
			invoiceAttachment.setInvoice_type(invoice_type);
			invoiceAttachment.setInvoice_code(invoice_code);
			invoiceAttachment.setInvoice_num(invoice_num);
			invoiceAttachment.setAttach_code(service.getNewAttachCode());//发票附近单号
			invoiceAttachment.setOrder_code(po.getOrder_sn());//所属订单号
			invoiceAttachment.setCustom_code(po.getCustom_code());//客户代码
			invoiceAttachment.setCreate_date(create_date);//附件日期　
			invoiceAttachment.setCreate_time(new Date());//制单时间
			invoiceAttachment.setSell_dep_code(po.getSell_dep_code());//销售部门代码
			invoiceAttachment.setAcc_period(po.getAcc_period());//财务核算期
			invoiceAttachment.setDepot_code(po.getDepot_code());//仓库代码
			invoiceAttachment.setCreater_code(UserShare.getCurrentUserCode(request));//制单人员代码（当前用户）
			invoiceAttachment.setAuthCoCode(po.getAuthCoCode());//所属公司代码
			//invoiceAttachment.setAuthDepCode(po.getAuthDepCode());//所属部门代码
			
			invoiceAttachment.setAcc_period(acc_period);
			invoiceAttachment.setSell_dep_code(sell_dep_code);
			invoiceAttachment.setSell_dep_id(sell_dep_id);
			
			service.add(invoiceAttachment);
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(), po.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(invoiceAttachment.getId());
				refGoods2.setInfo_type(RefGoodsType.INVOICE_ATTACHMENT_GOODS.getValue());
				refGoodsService.add(refGoods2);
			}
		}
		response.sendRedirect(req.getRefererURL());
	}
	
	

	//明细
	@RequestMapping("/getInvoiceAttachmentById")
	public ModelAndView getInvoiceAttachmentById(HttpServletRequest request, HttpServletResponse response)
	{
		InvoiceAttachment po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		po.setCustoms_name(customsService.getCustomName(false, 0, po.getCustom_code()));
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("dep", departmentsService.getByCode(po.getSell_dep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.INVOICE_ATTACHMENT_GOODS.getValue(), new Integer(String.valueOf(id)));
		result.addObject("refGoods", refGoods);		
		result.setViewName("/manage/sell/getInvoiceAttachmentById.jsp");
		return result;
	}
	
	
	//审核
	@RequestMapping("/auditInvoiceAttachment{viewName}")
	public ModelAndView auditInWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		InvoiceAttachment po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if("1".equals(viewName)){
			result = new ModelAndView();
			result.addObject("audit", "audit");
			result.addObject("po", po);
			result.setViewName("/manage/sell/getInvoiceAttachmentById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.INVOICE_ATTACHMENT_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setStatus(1);
				service.update(po);
				writer.write("审核成功！");
			}catch (Exception e) {
				e.printStackTrace();
				writer.write("审核失败！" + e.getCause());
			}
		}
		return result;
	}
	
	/*//记账
	@RequestMapping("/accInvoiceAttachment{viewName}")
	public ModelAndView accInWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		InvoiceAttachment po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if("1".equals(viewName)){
			result = new ModelAndView();
			result.addObject("acc", "acc");
			result.addObject("po", po);
			result.setViewName("/manage/sell/getInvoiceAttachmentById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.INVOICE_ATTACHMENT_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setStatus(3);
				service.update(po);//更新状态
				List<RefGoods> refgoodList = refGoodsService.getByInfoType(RefGoodsType.INVOICE_ATTACHMENT_GOODS.getValue(), po.getId());
				if (refgoodList!=null && refgoodList.size()!=0) {
					for (int i = 0; i < refgoodList.size(); i++) {
						RefGoods refGoods = (RefGoods)refgoodList.get(i);
						Goods goods = goodsService.getById(new Long(refGoods.getGoods_id()));
						*//**
						 * 记录到仓库帐中
						 *//*
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WarehouseAccounts warehouseAccounts = new WarehouseAccounts();
						warehouseAccounts.setAcc_period(po.getAcc_period());//财务统计核算期
						warehouseAccounts.setInfo_type("发票附件");//仓库帐类型
						warehouseAccounts.setGoods_sn(goods.getGoods_sn());//物料代码
						warehouseAccounts.setDep_code(po.getDepot_code());//仓库代码
						warehouseAccounts.setCreate_date(format.format(po.getCreate_date()));//入仓单日期
						warehouseAccounts.setCreate_time(format.format(po.getCreate_time()));//入仓库时间
						warehouseAccounts.setSys_date(format.format(new Date()));//生成仓库帐时间
						warehouseAccounts.setAmount(refGoods.getAmount());//物品数量
						warehouseAccounts.setStock_num(goods.getStock());//当前库存数量
						//warehouseAccounts.setSend_amount(0);//已下采购单要求送货数量, 根据采购单号 查询采购数量
						String remark = "单号："+po.getAttach_code()+"，部门："+po.getSell_dep_code()+"";
						warehouseAccounts.setRemark(remark);//凭证号（单号）、部门、客户等>
						warehouseAccountsService.add(warehouseAccounts);
					}
				}
				writer.write("记账成功！");
			}catch (Exception e) {
				e.printStackTrace();
				writer.write("记账失败！" + e.getCause());
			}
		}
		return result;
	}*/
	
	
}
